package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    //分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable int currentPage, @PathVariable int pageSize) throws IOException {

        IPage<User> page = new Page<>(currentPage, pageSize);

        userService.page(page, null);

        List<User> records = page.getRecords();

        long total = page.getTotal();

        PageBean<User> pageBean = new PageBean<>();

        pageBean.setRows(records);

        pageBean.setTotalCount(total);


        return new Result(Code.GET_OK, pageBean, "查询成功");
    }

    /**
     * 保存用户
     *
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody User user) {

        userService.save(user);

        return new Result(Code.SAVE_OK, "添加成功");

    }

    /**
     * 根据用户id查询用户
     *
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {

        User byId = userService.getById(id);

        userService.removeById(id);

        return new Result(Code.DELETE_OK, byId, "删除成功");


    }

    /**
     * 更新用户
     *
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {

        Integer id = user.getId();

        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();

        qw.eq(id != null, User::getId, id);

        userService.update(user, qw);

        if (id != null) {
            return new Result(Code.UPDATE_OK, "修改成功");
        } else {
            return new Result(Code.UPDATE_ERR, "被修改的用户不存在");
        }
    }

}
